import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import '../../data/api.dart';
import '../../res/appColor.dart';

import '../widgets/ProjectsListItem.dart';
import '../widgets/FilterBar.dart';
import '../widgets/FilterMenu.dart';
import '../../model/FilterBarModel.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int _page = 1;
  List _list = [];

  @override
  void initState() {
    super.initState();

    Api.getProjectsList(page: _page).then((response) {
      setState(() {
        _list = response.data['data']['projects_list'];
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.bColor,
      appBar: PreferredSize(
        child: AppBar(
          backgroundColor: AppColor.red,
          flexibleSpace: Stack(
            children: <Widget>[
              Positioned(
                child: Image.asset(
                  'assets/images/logo.png',
                  width: ScreenUtil().setWidth(100),
                ),
                left: ScreenUtil().setWidth(324),
                right: ScreenUtil().setWidth(324),
                bottom: ScreenUtil().setWidth(36),
              ),
            ],
          ),
        ),
        preferredSize: Size.fromHeight(ScreenUtil().setWidth(180)),
      ),
      body: ChangeNotifierProvider(
        create: (context) => FilterBarModel(),
        child: Stack(
          children: <Widget>[
            NestedScrollView(
              headerSliverBuilder: (context, boxIsScrolled) {
                return [
                  SliverToBoxAdapter(
                    child: Column(
                      children: <Widget>[
                        Search(),
                        Banner(),
                        Msg(),
                      ],
                    ),
                  ),
                ];
              },
              body: EasyRefresh.builder(
                builder: (context, physics, header, footer) {
                  return CustomScrollView(
                    slivers: <Widget>[
                      SliverPersistentHeader(
                        pinned: true,
                        delegate: _SliverAppBarDelegate(
                          minHeight: ScreenUtil().setWidth(90),
                          maxHeight: ScreenUtil().setWidth(90),
                          child: FilterBar(),
                        ),
                      ),
                      header,
                      SliverList(
                        delegate: SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                            return GestureDetector(
                              child: Container(
                                color: AppColor.white,
                                child: Column(
                                  children: <Widget>[
                                    PropertyListItem(
                                      data: _list[index],
                                    ),
                                    Offstage(
                                      child: Divider(
                                        indent: ScreenUtil().setWidth(28),
                                        endIndent: ScreenUtil().setWidth(28),
                                        thickness: ScreenUtil().setWidth(2),
                                        color: AppColor.bColor,
                                      ),
                                      offstage: index + 1 == _list.length,
                                    ),
                                  ],
                                ),
                              ),
                              onTap: () {
                                print('onTap SliverList Item: ' +
                                    index.toString());
                              },
                            );
                          },
                          childCount: _list.length,
                        ),
                      ),
                      footer,
                    ],
                    physics: physics,
                  );
                },
                onRefresh: () async {
                  await Future.delayed(Duration(seconds: 2), () {
                    if (mounted) {
                      _list = [];
                      _page = 1;

                      Api.getProjectsList(page: _page).then((response) {
                        setState(() {
                          _list = response.data['data']['projects_list'];
                        });
                      });
                    }
                  });
                },
                onLoad: () async {
                  await Future.delayed(Duration(seconds: 2), () {
                    if (mounted) {
                      _page++;
                      Api.getProjectsList(page: _page).then((response) {
                        setState(() {
                          List list = response.data['data']['projects_list'];
                          _list..addAll(list);
                        });
                      });
                    }
                  });
                },
              ),
            ),
            Consumer<FilterBarModel>(
              builder: (
                BuildContext context,
                FilterBarModel filterBarModel,
                Widget child,
              ) {
                return FilterMenu(index: filterBarModel.index);
              },
            ),
          ],
        ),
      ),
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => maxHeight;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}

class Msg extends StatelessWidget {
  const Msg({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: AppColor.white,
      margin: EdgeInsets.only(
        top: ScreenUtil().setWidth(20),
        bottom: ScreenUtil().setWidth(20),
      ),
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(
              left: ScreenUtil().setWidth(32),
              right: ScreenUtil().setWidth(28),
            ),
            child: Image.asset(
              'assets/images/msg.png',
              width: ScreenUtil().setWidth(56),
              height: ScreenUtil().setWidth(36),
            ),
          ),
          Container(
            color: AppColor.bColor,
            margin: EdgeInsets.only(
              right: ScreenUtil().setWidth(28),
            ),
            width: ScreenUtil().setWidth(2),
            height: ScreenUtil().setWidth(36),
          ),
          ConstrainedBox(
            child: Container(
              child: Swiper(
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          '2020唐山放假走向如何？',
                          style: TextStyle(
                            color: AppColor.textBlack,
                            fontSize: ScreenUtil().setWidth(28),
                          ),
                        ),
                        Text(
                          '2019-11-31',
                          style: TextStyle(
                            color: AppColor.textGray,
                            fontSize: ScreenUtil().setWidth(24),
                          ),
                        )
                      ],
                    ),
                  );
                },
                itemCount: 3,
                autoplay: true,
                scrollDirection: Axis.vertical,
              ),
            ),
            constraints: BoxConstraints.loose(
              Size(
                ScreenUtil().setWidth(580),
                ScreenUtil().setWidth(100),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class Banner extends StatelessWidget {
  const Banner({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ConstrainedBox(
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return Image.asset(
            'assets/tmp_images/3.png',
            width: ScreenUtil().setWidth(750),
            height: ScreenUtil().setWidth(400),
          );
//                  return Image.network(
//                    'https://via.placeholder.com/350x150',
//                    fit: BoxFit.fill,
//                  );
        },
        itemCount: 3,
        autoplay: true,
        pagination: SwiperPagination(
          builder: DotSwiperPaginationBuilder(
            color: AppColor.bColor_90,
            activeColor: AppColor.white,
            size: ScreenUtil().setWidth(8),
            activeSize: ScreenUtil().setWidth(8),
          ),
        ),
      ),
      constraints: BoxConstraints.loose(
        Size(
          ScreenUtil().setWidth(750),
          ScreenUtil().setWidth(400),
        ),
      ),
    );
  }
}

class Search extends StatelessWidget {
  const Search({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(
              top: ScreenUtil().setWidth(20),
              bottom: ScreenUtil().setWidth(20),
              left: ScreenUtil().setWidth(20)),
          child: Image.asset(
            'assets/images/pin.png',
            width: ScreenUtil().setWidth(30),
            height: ScreenUtil().setWidth(34),
          ),
        ),
        Container(
          margin: EdgeInsets.only(
              left: ScreenUtil().setWidth(10),
              top: ScreenUtil().setWidth(20),
              bottom: ScreenUtil().setWidth(20)),
          child: Text(
            '唐山',
            style: TextStyle(
              fontSize: ScreenUtil().setWidth(34),
            ),
          ),
        ),
        Expanded(
          child: Container(
            width: double.infinity,
            height: ScreenUtil().setWidth(68),
            margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
            alignment: Alignment.topLeft,
            decoration: BoxDecoration(
              color: AppColor.white,
              borderRadius: BorderRadius.all(
                Radius.circular(ScreenUtil().setWidth(8)),
              ),
            ),
            child: Container(
              margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
              height: ScreenUtil().setWidth(68),
              child: Row(
                children: <Widget>[
                  Image.asset(
                    'assets/images/magnifier.png',
                    width: ScreenUtil().setWidth(28),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
                    child: Text(
                      '输入小区名称',
                      style: TextStyle(
                        color: AppColor.textGray,
                        fontSize: ScreenUtil().setWidth(26),
                        height: 1.2,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}
